package main

import (
	"fmt"
	"sync"
	"time"
	"waether-push/service"

	"github.com/robfig/cron/v3"
)

var wg sync.WaitGroup

func main() {
	c := cron.New(cron.WithSeconds())

	spec := "0 10 7 * * ?" // 秒 分 时 日 月
	c.AddFunc(spec, run)

	c.Start()
	fmt.Printf("定时任务(%s)已开启，等待推送消息...", spec)

	select {}
}

func run() {
	// 获取微信Token
	accessToken := service.GetByAccessToken()
	if accessToken == "" {
		return
	}

	// 获取关注者列表
	followList := service.GetByFollowList(accessToken)
	if followList == nil {
		return
	}

	for _, v := range followList {
		go SendWeather(accessToken, "合肥", v.Str)
	}
	time.Sleep(time.Second * 5) // 交叉编译后Linux中无法执行wg，具体原因未知，故用此来约束
	wg.Wait()
	fmt.Println("Stop Goroutines")
}

// SendWeather 发送天气 XiaoJu
func SendWeather(accessToken, city, openid string) {
	wg.Add(1)
	fmt.Println("start wg", openid)
	defer wg.Done()

	weather := service.GetByWeather(city)
	// 发送模板消息
	data := `{
		"date":{"value":"` + weather.Date + " " + weather.Week + `", "color":"#173177"},
		"city":{"value":"` + weather.City + `", "color":"#173177"},
		"wea":{"value":"` + weather.Wea + `", "color":"#173177"},
		"tem":{"value":"` + weather.TemNight + " ~ " + weather.TemDay + `", "color":"#173177"},
		"win":{"value":"` + weather.Win + `", "color":"#173177"},
		"win_speed":{"value":"` + weather.WinSpeed + `", "color":"#173177"},
		"air":{"value":"` + weather.Air + `", "color":"#173177"},
		"pressure":{"value":"` + weather.Pressure + `", "color":"#173177"},
		"humidity":{"value":"` + weather.Humidity + `", "color":"#173177"},
		"update_time":{"value":"` + weather.UpdateTime + `", "color":"#173177"}
	}`

	fmt.Println(weather)

	service.PostTemplate(accessToken, data, service.TemplateID_Weather, openid)

	fmt.Println("SendWeather")
}
